/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.tukano.odt;

import it.tukano.fun.Tuple2;
import it.tukano.lang.StringExt;
import it.tukano.text.StringScanner;
import javax.swing.JCheckBox;

/**
 *
 * @author utente4
 */
public class OdtOptionalSectionEditor extends OdtFieldEditor {
    
    //Default serial version code
    private static final long serialVersionUID = 0;
    
    private final StringExt defaultValue;
    private JCheckBox component = new JCheckBox();
    
    public OdtOptionalSectionEditor(StringExt defaultValue) {
        this.defaultValue = defaultValue;
        component.setSelected(defaultValue != null && defaultValue.toBoolean(Boolean.FALSE));
        add(component);
    }

    @Override
    public void setValue(StringExt t) {
        component.setSelected(t != null && t.toBoolean(Boolean.FALSE));
    }

    @Override
    public Tuple2<StringExt, String> applyEditorValue(OdtField field, String xml) {
        if(field == null || xml == null) return Tuple2.newInstance(StringExt.wrap(component.isSelected()), xml);
        
        boolean keepSection = component.isSelected();
        StringExt s = StringExt.wrap(component.isSelected() ? "true": "false");
        if(keepSection) {
            xml = xml.replace(field.getToken(), "");
        } else {
            xml = eraseSection(field, xml);
        }
        return Tuple2.newInstance(s, xml);
    }
    
    protected String eraseSection(OdtField field, String xml) {
        int startIndex = xml.indexOf(field.getToken());
        int endIndex = xml.lastIndexOf(field.getToken());
        
        String parStart = "<text:p";
        String parEnd = "</text:p>";
        
        int removeStart = StringScanner.backIndexOf(xml, parStart, startIndex);
        int removeEnd = xml.indexOf(parEnd, endIndex) + parEnd.length();
        String removedSection = xml.substring(removeStart, removeEnd);
        xml = xml.substring(0, removeStart) + xml.substring(removeEnd, xml.length());
        return xml;
    }

    @Override
    public void clearValue() {
        component.setSelected(defaultValue != null && defaultValue.toBoolean(Boolean.FALSE));
    }
    
}
